import base64
import json
import requests
import pymysql
import os


os.environ['VAULT_TOKEN']='s.dzigDUueYlAtDd4isewAz3ml'

# 1.vault加密、解密接口调用
# curl --header "X-Vault-Token:$VAULT_TOKEN"
# --request POST --data '{"ciphertext":"vault:v1:3AJH0GG6JSUDLLqlEhgCgnvamtXXlIxvDqnVy8yqYuO9uf/tQbM0"}'
# http://127.0.0.1:8200/v1/encryption/decrypt/datakey

def encrypt(encoding_vaule):
    # vault加密接口
    url = "http://127.0.0.1:8200/v1/encryption/encrypt/datakey"
    header = {"X-Vault-Token":"s.dzigDUueYlAtDd4isewAz3ml"}
    data = {"plaintext":encoding_vaule}
    req = requests.post(url=url,headers=header,data=data)
    cipher_text = json.loads(req.text).get("data").get("ciphertext")

    return cipher_text

def decrypt(cipher_text):
    # vault解密接口
    url = "http://127.0.0.1:8200/v1/encryption/decrypt/datakey"
    header = {"X-Vault-Token": "s.dzigDUueYlAtDd4isewAz3ml"}
    data = {"ciphertext": cipher_text}
    req = requests.post(url=url, headers=header, data=data)
    result = json.loads(req.text).get("data").get("plaintext")
    plain_text = base64.b64decode(result).decode("utf-8")

    return plain_text

# if __name__ == '__main__':
#
#     # 从Vault 获取数据库动态凭证，接口：http://127.0.0.1:8200/v1/database/creds/my-ro
#     username_password_url = 'http://127.0.0.1:8200/v1/database/creds/my-ro'
#     resp = requests.get(url=username_password_url, headers={"X-Vault-Token": os.environ['VAULT_TOKEN']}).text
#     db_user = json.loads(resp).get('data').get('username')
#     db_password = json.loads(resp).get('data').get('password')
#
#     # 建立数据库链接，读取数据库字段
#     conn = pymysql.connect(host='127.0.0.1', user=db_user, password=db_password, port=3307, database='demo_enc')
#     cursor = conn.cursor()
#     sql = '''select * from t_encrypt'''
#     cursor.execute(sql)
#     # # conn.commit()
#     results = cursor.fetchall()
#     conn.close()
#
#     for item in results:
#         encoding_phone = base64.b64encode(item[2].encode('utf-8'))
#         cipher_phone = encrypt(encoding_phone)
#         plain_text = decrypt(cipher_phone)
#         print("数据库明文>>>: ",item[2],"加密后密文>>>: ",cipher_phone,"解密后明文>>>:",plain_text)
